<!--
 * @Description: 意见征询
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2022-10-13 15:09:10
 * @LastEditTime: 2022-12-01 17:38:31
 * @FilePath: \cscec-pms-admin\src\views\matters\approval\components\consultation\index.vue
-->
<template>
  <div>
    <title-name
      title="意见征询列表"
      v-if="isShowBtn"
    />
    <!-- 意见征询列表 -->
    <a-table
      :row-key="'id'"
      :scroll="{ x: 800 }"
      :columns="columns"
      :data-source="data"
      :loading="loading"
      bordered
      :pagination="false"
      class="consultation-table"
    >
      <template
        slot="opinions"
        slot-scope="text"
      >
        <a-tooltip :title="text">
          <span class="ellipsis-span">{{text}}</span>
        </a-tooltip>
      </template>
      <template
        slot="replyOpinions"
        slot-scope="text"
      >
        <a-tooltip :title="text">
          <span class="ellipsis-span">{{text}}</span>
        </a-tooltip>
      </template>
    </a-table>
    <div
      v-if="isShowBtn"
      class="consultation-btn"
    >
      <!-- 流程监控 -->
      <template v-if="isMonitoring">
        <a-button @click="handleProcessRemove">
          流程清除
        </a-button>
        <a-button @click="handelReturnToStart">
          退回至起始状态
        </a-button>
        <a-button @click="handelReturnToPrevious">
          退回至上一级
        </a-button>
      </template>
      <!-- 流程监控 -->
      <!-- 默认审批 -->
      <template v-else>
        <a-tooltip
          v-if="isApprover && !isLastTask"
          placement="top"
        >
          <template
            v-if="!!subordinateApproverText && approverList.length > 2"
            slot="title"
          >
            <span>{{ subordinateApproverText }}</span>
          </template>
          <a-button
                  type="primary"
            :disabled="!hasApprover"
            @click="selectSubordinateApproverVisible = true"
          >
            选择下级审批人（目前：{{ subordinateApproverTextOmit }}）
          </a-button>
        </a-tooltip>
        <a-button @click="selectConsultationVisible = true" type="primary">
          意见征询
        </a-button>
        <template v-if="isTurnTo !== '' && displayRransfer">
          <a-button
                  type="primary"
            v-if="isTurnTo"
            @click="handelTurnToRecall"
          >
            转办退回
          </a-button>
          <a-button
                  type="primary"
            v-else
            @click="selectTurnToVisible = true"
          >
            转办
          </a-button>
        </template>
        <!-- 审批按钮插槽 -->
        <slot name="approverButton" />
        <!-- 审批按钮插槽 -->
      </template>
      <!-- 默认审批 -->
    </div>
    <!-- 意见征询列表 -->
    <!-- 选择下级审批人模态框 -->
    <SelectSubordinateApprover
      :visible.sync="selectSubordinateApproverVisible"
      :subordinate-approver-list.sync="subordinateApproverList"
    />
    <!-- 选择下级审批人模态框 -->
    <!-- 意见征询模态框 -->
    <SelectConsultation
      :visible.sync="selectConsultationVisible"
      :info="info"
      @refresh="getData()"
    />
    <!-- 意见征询模态框 -->
    <!-- 转办人选择模态框 -->
    <SelectTurnTo
      :visible.sync="selectTurnToVisible"
      :task-name="taskName"
      :info="info"
    />
    <!-- 转办人选择模态框 -->
  </div>
</template>
<script>
import { columns } from './model.js'
import { getByProcInstId, getConfig, getNextAssign, lastTask, tranfer, tranferTaskRecall, deleteProcess, recallPrevTask } from '@/api/process'
import { recall } from '@/api/indexPage'
import SelectSubordinateApprover from './SelectSubordinateApprover'
import SelectConsultation from './SelectConsultation'
import SelectTurnTo from './SelectTurnTo'
import Vue from 'vue'
import { notifyParentWindow } from '@/utils/util.js'
export default {
  name: 'Consultation',
  components: {
    SelectSubordinateApprover,
    SelectConsultation,
    SelectTurnTo
  },
  props: {
    // 流程id
    procInstId: {
      type: String,
      require: true,
      default: ''
    },
    // 是否显示按钮
    isShowBtn: {
      type: Boolean,
      default: true
    },
    // 当前节点
    taskName: {
      type: String,
      require: true,
      default: ''
    },
    // 下级审批人
    subApproverList: {
      type: Array,
      default: () => []
    },
    //是否显示转办按钮
    displayRransfer:{
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 路由参数
      query: this.$route.query,
      // 表头
      columns,
      // 列表数据
      data: [],
      // 列表加载中
      loading: false,
      //下级审批人模态框显示隐藏
      selectSubordinateApproverVisible: false,
      // 下级审批人列表
      subordinateApproverList: [],
      // 审批配置信息
      approverConfig: [],
      // 是否最后一个审批节点
      isLastTask: false,
      // 意见征询模态框显示隐藏
      selectConsultationVisible: false,
      // 转办人模态框显示隐藏
      selectTurnToVisible: false,
      // 是否转办
      isTurnTo: '',
      // 登录人信息
      info: Vue.getAcloudProvider().getUserInfo()
    }
  },
  computed: {
    // 节点岗位是否有人员
    hasApprover() {
      return this.subordinateApproverList.map((el) => el?.assign || []).flat().length > 0
    },
    // 已选择下级审批人列表
    approverList: {
      get() {
        this.$emit('update:subApproverList', this.subordinateApproverList)
        return this.subordinateApproverList.map((el) => el?.approver || []).flat()
      }
    },
    // 下级审批人文本
    subordinateApproverText() {
      try {
        return this.approverList.map((el) => el?.label.trim()).join('、')
      } catch (error) {
        return ''
      }
    },
    // 下级审批人按钮文本
    subordinateApproverTextOmit() {
      return `${this.approverList
        .slice(0, 2)
        .map((el) => el?.label)
        .join('、')}${this.approverList.length > 2 ? '...' : ''}`
    },
    // 是否流程监控
    isMonitoring() {
      return this.query?.isMonitoring || false
    },
    // 是否提交选择审批人('SUMBIT_ASSIGN'是否提交选择审批人字段名,'0':否,'1':是)
    isApprover() {
      return this.approverConfig.find((el) => el.keyCol === 'SUMBIT_ASSIGN')?.keyValue === '1'
    }
  },
  mounted() {
    this.getData()
    // false：默认审批按钮,true:流程监控
    if (!this.isMonitoring && this.isShowBtn) {
      this.getApproverConfig()
      this.getSubordinateApproverList()
      this.getLastTask()
      this.getIsTurnTo()
    }
  },
  watch: {
    //监听路由变化，动态查询
    $route: {
      handler: function (val, oldVal) {
        val.query?.procInstId && this.getData(val.query?.procInstId)
      },
      // 深度观察监听
      deep: true
    }
  },
  methods: {
    /**
     * @description: 获取列表数据
     * @return {void}
     */
    getData(id) {
      let procInstId = id ? id : this.procInstId
      if (!procInstId) {
        console.log('没有procInstId，不能查询意见征询列表')
        return
      }
      this.loading = true
      getByProcInstId(procInstId)
        .then((res) => {
          if (res.code === this.SUCCESS_CODE) {
            this.data = res.data
            this.$emit('getData', this.data)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * @description: 获取审批配置信息
     * @return {void}
     */
    getApproverConfig() {
      getConfig({ processKey: this.query.processKey }).then((res) => {
        if (res.code === this.SUCCESS_CODE) {
          this.approverConfig = res.data
        }
      })
    },
    /**
     * @description: 获取下级审批人列表
     * @return {void}
     */
    async getSubordinateApproverList() {
      // getNextAssign({
      //   taskId: this.query.taskId,
      //   current: true
      // }).then((res) => {
      //   if (res.code === this.SUCCESS_CODE) {
      //     this.subordinateApproverList = res.data.map((el) => {
      //       if ((el?.approver || []).length === 0) {
      //         el.approver = el.assign.map((item) => {
      //           return {
      //             key: item.userId,
      //             label: item.name
      //           }
      //         })
      //       }
      //       return el
      //     })
      //   }
      // })
      const res = await getNextAssign({
        taskId: this.query.taskId,
        current: false
      })
      if (res.code === this.SUCCESS_CODE) {
        const res1 = await getNextAssign({
          taskId: this.query.taskId,
          current: true
        })
        if (res1.code === this.SUCCESS_CODE) {
          this.subordinateApproverList = res.data.map((el, index) => {
            if ((el?.approver || []).length === 0) {
              el.approver = res1.data[index].assign.map((item) => {
                return {
                  key: item.userId,
                  label: item.name
                }
              })
            }
            return el
          })
        }
      }
    },
    /**
     * @description: 获取是否最后一个审批节点
     * @return {void}
     */
    getLastTask() {
      lastTask({ procInstId: this.procInstId, taskDefinitionKey: this.query.taskDefKey }).then((res) => {
        if (res.code === this.SUCCESS_CODE) {
          this.isLastTask = res.data
        }
      })
    },
    /**
     * @description: 获取是否转办
     * @return {void}
     */
    getIsTurnTo() {
      const { id: userId } = this.info
      tranfer({ taskId: this.query.taskId, userId }).then((res) => {
        if (res.code === this.SUCCESS_CODE) {
          this.isTurnTo = res.data
        }
      })
    },
    /**
     * @description: 转办退回
     * @return {void}
     */
    handelTurnToRecall() {
      this.$confirm({
        title: '警告提醒！',
        content: '确定审批退回？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return new Promise(async (resolve) => {
            try {
              const res = await tranferTaskRecall({
                taskId: this.query.taskId
              })
              if (res.data.code === this.SUCCESS_CODE) {
                this.$message.success('退回成功')
                notifyParentWindow()
                window.close()
              }
              resolve()
            } catch (error) {
              console.log(error)
              resolve()
            }
          })
        }
      })
    },
    /**
     * @description: 流程清除
     * @return {void}
     */
    handleProcessRemove() {
      this.$confirm({
        title: '警告提醒！',
        content: '是否流程清除?',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return new Promise(async (resolve) => {
            try {
              const res = await deleteProcess({
                procInstId: this.query.procInstId
              })
              if (res.data.code === this.SUCCESS_CODE) {
                this.$message.success('清除成功')
                notifyParentWindow()
                window.close()
              }
              resolve()
            } catch (error) {
              console.log(error)
              resolve()
            }
          })
        }
      })
    },
    /**
     * @description: 退回至起始状态
     * @return {void}
     */
    handelReturnToStart() {
      this.$confirm({
        title: '警告提醒！',
        content: '确定审批退回？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return new Promise(async (resolve) => {
            try {
              const { id: userId } = this.info
              const res = await recall({
                formData: {
                  opinions: '退回至草稿或过程性状态'
                },
                procInstId: this.query.procInstId,
                userId,
                // 我发起: 0,管理员撤回: 1
                type: 1,
                taskId: this.query.taskId
              })
              if (res.code === this.SUCCESS_CODE) {
                this.$message.success('撤回成功')
                notifyParentWindow()
                window.close()
              }
              resolve()
            } catch (error) {
              console.log(error)
              resolve()
            }
          })
        }
      })
    },
    /**
     * @description: 退回至上一级
     * @return {void}
     */
    handelReturnToPrevious() {
      this.$confirm({
        title: '警告提醒！',
        content: '确定审批退回？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return new Promise(async (resolve) => {
            try {
              const { id: userId } = this.info
              const res = await recallPrevTask({
                taskId: this.query.taskId,
                userId
              })
              if (res.data.code === this.SUCCESS_CODE) {
                this.$message.success('退回成功')
                notifyParentWindow()
                window.close()
              }
              resolve()
            } catch (error) {
              console.log(error)
              resolve()
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.consultation-table {
  margin-bottom: 20px;
}
.consultation-btn {
  display: flex;
  justify-content: flex-end;
  .ant-btn {
    margin-right: 20px;
  }
  & > .ant-btn:nth-last-of-type(1) {
    margin-right: 0;
  }
}
</style>
